<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-tabs v-model="activeName">
      <el-tab-pane
        v-for="paneName in paneNames"
        :key="paneName"
        :name="paneName"
        :label="$t(`cms.menu.crawler.config.${paneName}`)"
      />
    </el-tabs>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <template v-if="activeName === 'base'">
        <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="formData.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="目标栏目" prop="targetChannelId" :rules="[
            { required: true, message: () => t('common.required') },
            {
              validator: (rule, value, callback) => {
                if (channelList.find((it) => it.id === value)?.children.length > 0) {
                  callback(t('cms.content.error.onlyLeafChannel'))
                  return
                }
                callback()
              }
            }
          ]">
          <el-tree-select
              v-model="formData.targetChannelId"
              :data="channelList"
              node-key="id"
              :props="{ label: 'name' }"
              :render-after-expand="false"
              class="w-full"
          />
        </el-form-item>
        <el-form-item label="采集url" prop="crawlerUrl">
          <el-input v-model="formData.crawlerUrl" placeholder="请输入采集url  ${pageNo} 是分页数字替换变量"  type="textarea" />
        </el-form-item>
        <el-form-item label="采集区块" prop="blockXpath">
          <el-input v-model="formData.blockXpath" placeholder="请输入要采集的内容列表区域xpath"  type="textarea" />
        </el-form-item>
        <el-form-item label="采集顺序" prop="crawlerSort">
          <el-radio-group v-model="formData.crawlerSort">
            <el-radio
              v-for="dict in getIntDictOptions(DICT_TYPE.CMS_CRAWLER_SORT)"
              :key="dict.label"
              :value="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="页码" prop="startPage">
          <el-input-number v-model="formData.startPage" placeholder="请输入开始页码" :min="0"  controls-position="right" />
          <el-input-number v-model="formData.endPage" placeholder="请输入结束页码" :min="0"  controls-position="right" />
        </el-form-item>
        <el-form-item label="资源补齐前缀补全" prop="urlPrefix">
          <el-input v-model="formData.resUrlPrefix" placeholder="请输入资源补齐前缀补全"  type="textarea" />
        </el-form-item>
        <el-form-item label="采集下载资源" prop="downloadRes">
          <el-radio-group v-model="formData.downloadRes">
            <el-radio
              v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
              :key="dict.label"
              :value="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="发布时间格式" prop="releaseTimeFormat">
          <el-input v-model="formData.releaseTimeFormat" placeholder="请输入发布时间格式" />
        </el-form-item>
        <el-form-item label="任务线程数" prop="totalThread">
          <el-input v-model="formData.totalThread" placeholder="请输入任务线程数" />
        </el-form-item>
        <el-form-item label="超时等待时间(秒)" prop="timeoutSecond">
          <el-input v-model="formData.timeoutSecond" placeholder="请输入超时等待时间(秒)" />
        </el-form-item>
        
      </template>
      <template v-if="activeName === 'contentRule'">
        <el-form-item label="标题" >
          <el-input v-model="formData.contentRule.titleXpath" placeholder="标题Xpath"  type="textarea" resizeTextarea rows="3" cols="5"/>
        </el-form-item>
        <el-form-item label="内容" >
          <el-input v-model="formData.contentRule.textXpath" placeholder="内容Xpath"  type="textarea" resizeTextarea rows="3" cols="5"/>
         </el-form-item>
        <el-form-item label="发布时间" >
          <el-input v-model="formData.contentRule.releaseTimeXpath" placeholder="发布时间Xpath"  type="textarea" resizeTextarea rows="3" cols="5"/>
        </el-form-item>
        <el-form-item label="作者" >
          <el-input v-model="formData.contentRule.authorXpath" placeholder="作者Xpath"  type="textarea" resizeTextarea rows="3" cols="5"/>
        </el-form-item>
        <el-form-item label="来源" >
          <el-input v-model="formData.contentRule.sourceXpath" placeholder="来源Xpath"  type="textarea" resizeTextarea rows="3" cols="5"/>
        </el-form-item>
        <el-form-item label="摘要" >
          <el-input v-model="formData.contentRule.descriptionXpath" placeholder="摘要Xpath"  type="textarea" resizeTextarea rows="3" cols="5"/>
        </el-form-item>
        <el-form-item label="浏览量" >
          <el-input v-model="formData.contentRule.viewXpath" placeholder="摘要Xpath"  type="textarea" resizeTextarea rows="3" cols="5"/>
        </el-form-item>
      </template>
      
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { CrawlerTaskApi, CrawlerTaskVO } from '@/api/cms/crawlertask'
import { DICT_TYPE, getIntDictOptions,getBoolDictOptions } from '@/utils/dict'
import { toTree } from '@/utils/cmstree'
import * as ChannelApi from '@/api/cms/channel'

/** 采集任务 表单 */
defineOptions({ name: 'CrawlerTaskForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const paneNames = ref(['base', 'contentRule'])
const activeName = ref('base') //选项卡

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  taskName: undefined,
  releaseTimeFormat: undefined,
  targetChannelId: undefined,
  downloadRes: true,
  crawlerUrl: undefined,
  crawlerSort: 1,
  startPage: 0,
  endPage: 1,
  totalThread: 1,
  timeoutSecond: 5,
  contentRule: {},
  excludeRule: undefined,
  urlPrefix: undefined
})
const formRules = reactive({
  taskName: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  targetChannelId: [{ required: true, message: '目标栏目id不能为空', trigger: 'blur' }],
  downloadRes: [{ required: true, message: '采集下载资源不能为空', trigger: 'blur' }],
  crawlerSort: [{ required: true, message: '采集顺序(1倒叙 0正序)不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  await fetchChannelList()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CrawlerTaskApi.getCrawlerTask(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CrawlerTaskVO
    if (formType.value === 'create') {
      await CrawlerTaskApi.createCrawlerTask(data)
      message.success(t('common.createSuccess'))
    } else {
      await CrawlerTaskApi.updateCrawlerTask(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    taskName: undefined,
    releaseTimeFormat: undefined,
    targetChannelId: undefined,
    downloadRes: true,
    crawlerUrl: undefined,
    crawlerSort: 1,
    startPage: 0,
    endPage: 1,
    totalThread: 1,
    timeoutSecond: 5,
    contentRule: {},
    excludeRule: undefined,
    urlPrefix: undefined
  }
  formRef.value?.resetFields()
}
const channelList = ref<any[]>([])
const flatChannelList = ref<any[]>([])
const fetchChannelList = async () => {
  flatChannelList.value = await ChannelApi.getContentChannelTreeApi()
  channelList.value = toTree(flatChannelList.value)
}
</script>
